import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:amway_superapp_creator_plugin/analysis/zhuge_circle.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/config/enum_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';
import 'package:amway_superapp_creator_plugin/dialog/common_bottom_sheet.dart';
import 'package:amway_superapp_creator_plugin/dialog/loading_dialog.dart';
import 'package:amway_superapp_creator_plugin/models/circle_detail_model.dart';
import 'package:amway_superapp_creator_plugin/models/create_user_info_model.dart';
import 'package:amway_superapp_creator_plugin/net/http_manager.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/image_pickasset_util.dart';
import 'package:amway_superapp_creator_plugin/utils/sp_util.dart';
import 'package:amway_superapp_creator_plugin/utils/throttle.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/utils/upload_image_utils.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';
import 'package:amway_superapp_creator_plugin/views/circle/event.dart';
import 'package:amway_superapp_creator_plugin/widget/drag_sort_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:photo_manager/photo_manager.dart';

import '../image_bean.dart';
import 'related_shop.dart';

class SendEditerPageView extends StatefulWidget {
  bool isNewAdd = true;
  bool isUserDraft = false;
  CircleDetailData circleData;
  String amwayAda;
  String amwayId;
  int circleState = 0; //1审核不通过 2待发布
  List<ImageBean> images = [];
  bool isDetailEdit = false;

  SendEditerPageView({
    this.isNewAdd,
    this.isUserDraft,
    this.circleData,
    this.amwayAda,
    this.circleState = 0,
    this.amwayId,
    this.images,
  });

  @override
  _SendEditerPageViewState createState() => _SendEditerPageViewState();
}

class _SendEditerPageViewState extends State<SendEditerPageView> {
  int moveAction = MotionEvent.actionUp;
  bool _canDelete = false;
  FocusNode _titleNode = FocusNode();
  FocusNode _descNode = FocusNode();
  List<ImageBean> imageList = List();
  TextEditingController _titleController;
  TextEditingController _descController;
  Size size;

  @override
  void initState() {
    super.initState();
    if (null != widget.circleData &&
        null != widget.circleData.medias &&
        widget.circleData.medias.length > 0) {
      widget.circleData.medias.forEach((element) {
        imageList.add(ImageBean(
            path: element.data, state: element.state, type: element.dataType));
      });
    }
    if (null != widget.images && widget.images.length > 0) {
      imageList = widget.images;
    }

    _titleController = TextEditingController(text: widget.circleData.title);
    _titleController.addListener(() {
      String current = _titleController.text;
      widget.circleData.title = current;
    });
    _descController =
        TextEditingController(text: widget.circleData.description);
    _descController.addListener(() {
      String current = _descController.text;
      widget.circleData.description = current;
    });
    num = widget.circleData.description.length;
    if (!widget.isNewAdd) {
      widget.isDetailEdit = false;
    } else {
      widget.isDetailEdit = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    size = MediaQuery
        .of(context)
        .size;

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        brightness: Brightness.light,
        backgroundColor: Colors.white,
        leading: _buildeAppBarleading(context),
        title: Text(
          '编辑动态',
          style: TextStyle(
              color: ColorsConfig.c_2c2c2c, fontSize: ScreenUtil().setSp(20)),
        ),
      ),
      body: buildeBody(context),
      bottomNavigationBar: _builderBottomBar(context),
    );
  }

  Widget _buildeAppBarleading(BuildContext context) {
    return IconButton(
      onPressed: () {
        _closeFocus();
        if (widget.isNewAdd) {
          if (widget.circleData.title.isEmpty &&
              widget.circleData.description.isEmpty) {
            if (imageList.length == 0) {
              Application.router.pop(context);
            } else {
              _saveDraft();
            }
          } else {
            _saveDraft();
          }
        } else {
          if (widget.circleState == 1) {
            _unPassBack();
          } else if (widget.circleState == 2) {
            _unPassBack();
          } else {
            _clear();
            Application.router.pop(context);
          }
        }
      },
      icon: Image.asset(
        'picture/icon_back.png',
        package: 'amway_superapp_creator_plugin',
      ),
    );
  }

  Widget buildeBody(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _closeFocus();
      },
      child: WillPopScope(
        onWillPop: () {
          _closeFocus();
          if (widget.isNewAdd) {
            if (widget.circleData.title == "" &&
                widget.circleData.description == "") {
              if (imageList.length == 0) {
                Application.router.pop(context);
              } else {
                _saveDraft();
              }
            } else {
              _saveDraft();
            }
          } else {
            if (widget.circleState == 1) {
              _unPassBack();
            } else if (widget.circleState == 2) {
              _unPassBack();
            } else {
              _clear();
              Application.router.pop(context);
            }
          }
          return;
        },
        child: _builderBodyWidget(context),
      ),
    );
  }

  bool shopChanged = false;

  Widget _builderBodyWidget(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildeTopEditContent(context),
          RelatedShop(
            widget.circleData,
            setFocus: () {
              _closeFocus();
            },
            back: (value) {
              if (value != null) {
                setState(() {
                  widget.isDetailEdit = true;
                  shopChanged = true;
                });
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildeTopEditContent(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(ScreenUtil().setWidth(15)),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
                color: ColorsConfig.c_14000000,
                offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                blurRadius: 12.0, //阴影模糊程度
                spreadRadius: 0.0 //阴影扩散程度
            )
          ]),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _builderTopTitleWidget(context),
          _builderLine(context),
          _builderTopContentWidget(context),
          _builderLine(context),
          _builderTopContentNumWidget(context),
          _builderDragSortView(context),
        ],
      ),
    );
  }

  bool hasTitle = true;

  Widget _builderTopTitleWidget(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setWidth(20),
          top: 0,
          bottom: 0),
      child: Row(
        children: [
          Expanded(
              flex: 1,
              child: TextField(
                onChanged: (value) {
                  setState(() {
                    if (widget.circleData.titleVerify == 3) {
                      widget.circleData.titleVerify = 0;
                    }
                    hasTitle = true;
                    widget.isDetailEdit = true;
                  });
                },
                keyboardAppearance: Brightness.light,
                controller: _titleController,
                focusNode: _titleNode,
                maxLines: 1,
                enabled: widget.isNewAdd == false &&
                    widget.circleData.titleVerify != null &&
                    widget.circleData.titleVerify == 1
                    ? false
                    : true,
                inputFormatters: [LengthLimitingTextInputFormatter(18)],
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(0),
                  border: InputBorder.none,
                  hintText: '输入标题，最长18字',
                  hintStyle: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: hasTitle == true
                        ? ColorsConfig.c_4D2C2C2C
                        : ColorsConfig.c_cd0000,
                    fontSize: ScreenUtil().setSp(18),
                  ),
                ),
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: ScreenUtil().setSp(18),
                  color: ColorsConfig.c_2c2c2c,
                ),
              )),
          widget.isNewAdd == false && widget.circleData.titleVerify != null
              ? _verify(widget.circleData.titleVerify)
              : Container(),
          GestureDetector(
            onPanDown: (_) {
              _titleController.clear();
              setState(() {});
            },
            child: Container(
              child: _titleNode.hasFocus == true &&
                  widget.circleData.title != null &&
                  widget.circleData.title.length > 0
                  ? Icon(
                Icons.cancel,
                size: ScreenUtil().setSp(25),
                color: Colors.black45,
              )
                  : Text(""),
            ),
          ),
        ],
      ),
    );
  }

  Widget _builderLine(BuildContext context) {
    return Container(
        margin: EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(15)),
        child: Divider(
          height: 1.0,
          color: ColorsConfig.c_14000000,
        ));
  }

  bool hasDes = true;

  Widget _builderTopContentWidget(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setWidth(20),
          top: 0,
          bottom: 0),
      child: Stack(alignment: Alignment.bottomRight, children: [
        widget.circleData.descriptionVerify == 1 ||
            widget.circleData.descriptionVerify == 3
            ? _verify(widget.circleData.descriptionVerify) //编辑状态 审核中或者审核未通过
            : Text(""),
        TextField(
          minLines: 4,
          maxLines: 8,
          keyboardAppearance: Brightness.light,
          focusNode: _descNode,
          onChanged: (value) {
            setState(() {
              if (widget.circleData.descriptionVerify == 3) {
                widget.circleData.descriptionVerify = 0;
              }
              num = value.isNotEmpty ? value.length : 0;
              hasDes = true;
              widget.isDetailEdit = true;
            });
          },
          controller: _descController,
          style: TextStyle(
              color: num > 1000 ? ColorsConfig.c_c53434 : ColorsConfig.c_2c2c2c,
              fontSize: ScreenUtil().setSp(16)),
          enableInteractiveSelection: widget.isNewAdd == false &&
              widget.circleData.descriptionVerify != null &&
              widget.circleData.descriptionVerify == 1
              ? false
              : true,
          onTap: () {
            if (widget.isNewAdd == false &&
                widget.circleData.descriptionVerify != null &&
                widget.circleData.descriptionVerify == 1) {
              _descNode.unfocus();
            }
          },
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '添加正文',
            hintStyle: TextStyle(
              color: hasDes == true
                  ? ColorsConfig.c_4D2C2C2C
                  : ColorsConfig.c_cd0000,
              fontSize: ScreenUtil().setSp(16),
            ),
          ),
          textAlign: TextAlign.left,
        )
      ]),
    );
  }

  Widget _builderTopContentNumWidget(BuildContext context) {
    return widget.circleData.descriptionVerify == 1 ||
        widget.circleData.descriptionVerify == 3
        ? Container()
        : Container(
      alignment: Alignment.topRight,
      padding: EdgeInsets.only(
          right: ScreenUtil().setWidth(20),
          top: ScreenUtil().setHeight(5),
          bottom: ScreenUtil().setHeight(5)),
      width: double.infinity,
      child: Text(
        '${num}/1000',
        textAlign: TextAlign.right,
        style: TextStyle(
            fontSize: ScreenUtil().setSp(14),
            color: num > 1000
                ? ColorsConfig.c_c53434
                : ColorsConfig.c_4D2C2C2C),
      ),
    );
  }

  Widget _builderDragSortView(BuildContext context) {
    final width = window.physicalSize.width;

    print("----${width}");
    return DragSortView(
      imageList,
      space: 5,
      width: width / 3 - ScreenUtil().setWidth(35),
      padding: EdgeInsets.symmetric(horizontal: ScreenUtil().setWidth(10),
          vertical: ScreenUtil().setHeight(10)),

      itemBuilder: (BuildContext context, int index) {
        // It is recommended to use a thumbnail picture
        return _builderImageItem(context, index);
      },
      initBuilder: (BuildContext context) {
        return _builderAddImageWidget(context);
      },
      onDragRemovedListener: (index) {
        widget.circleData.medias.removeAt(index);
        setState(() {
          widget.isDetailEdit = true;
          imageChanged = true;
        });
      },
      onDragListener: (MotionEvent event, double itemWidth) {
        switch (event.action) {
          case MotionEvent.actionDown:
            _closeFocus();
            moveAction = event.action;
            setState(() {});
            break;
          case MotionEvent.actionMove:
            double x = event.globalX + itemWidth;
            double y = event.globalY + itemWidth;
            double maxX = MediaQuery
                .of(context)
                .size
                .width -
                1 * ScreenUtil().setWidth(200);
            double maxY = MediaQuery
                .of(context)
                .size
                .height -
                1 * ScreenUtil().setHeight(200);
            print('Sky24n maxX: $maxX, maxY: $maxY, x: $x, y: $y');
            if (_canDelete && (x < maxX || y < maxY)) {
              setState(() {
                _canDelete = false;
              });
            } else if (!_canDelete && x > maxX && y > maxY) {
              setState(() {
                _canDelete = true;
              });
            }
            break;
            break;
          case MotionEvent.actionUp:
            moveAction = event.action;
            if (_canDelete) {
              setState(() {
                _canDelete = false;
              });
              return true;
            } else {
              widget.circleData.medias.clear();
              imageList.forEach((element) {
                widget.circleData.medias.add(ImagesBean(
                    dataType: "IMAGE",
                    data: element.path == null || element.path == ""
                        ? element.file.path
                        : element.path));
              });
              setState(() {});
            }
            break;
        }
        return false;
      },
    );
  }

  bool imageChanged = false;

  Widget _builderImageItem(BuildContext context, index) {
    ImageBean imageBean = imageList[index];
    return InkWell(
      onTap: () {
        _closeFocus();
        Map<String, dynamic> parameters = {
          "index": index,
          "imageList": imageList,
        };
        widget.isDetailEdit = true;
        ZhugeCircleAnalysis.circleAddCover("编辑动态");
        Application.router
            .navigateTo(context, Routes.MULTIMEADIAPREVIEW,
            routeSettings: RouteSettings(arguments: parameters))
            .then((value) {
          if (null != value && value is List) {
            setState(() {
              imageList = value;
              imageChanged = true;
            });
          }
        });
      },
      child: ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: AspectRatio(
            aspectRatio: 1.1,
            child: imageBean.path != null && imageBean.path.isNotEmpty
                ? _builderImageStateWidget(imageBean)
                : Image.file(

              imageBean.file == null
                  ? File(imageBean.path)
                  : imageBean.file,
              fit: BoxFit.cover,
            ),
          )

      ),


    );
  }

  Widget _builderImageStateWidget(ImageBean imageBean) {
    return Stack(
      fit: StackFit.expand,
      children: [
        imageBean.path.startsWith("http")
            ? Image.network(
          imageBean.path,
          fit: BoxFit.fill,
        )
            : Image.file(
          File(imageBean.path),
          fit: BoxFit.fill,
        ),
        _verify(imageBean.state),
      ],
    );
  }

  Widget _verify(int state) {
    return Container(
        child: state == 1
            ? Image.asset(
          "picture/icon_under_review.png",
          package: 'amway_superapp_creator_plugin',
          width: ScreenUtil().setWidth(80),
          height: ScreenUtil().setWidth(30),
        )
            : state == 3
            ? Image.asset(
          "picture/icon_audit_nopass.png",
          package: 'amway_superapp_creator_plugin',
          width: ScreenUtil().setWidth(80),
          height: ScreenUtil().setWidth(30),
        )
            : Text(""));
  }

  Widget _builderAddImageWidget(BuildContext context) {
    return InkWell(
      onTap: () {
        isAddImage = true;
        _closeFocus();
        _loadAssets(context);
      },
      child: Container(
        child: Image.asset(
          isAddImage ? "picture/add_img.png" : "picture/icon_add_no_image.png",
          package: "amway_superapp_creator_plugin",
          fit: BoxFit.contain,
        ),
      ),
    );
  }

  bool isAddImage = true;

  Widget _builderBottomBar(BuildContext context) {
    return SizedBox(
      height: ScreenUtil().setWidth(122),
      child: Stack(
        children: [
          _builderBottomTip(context),
          _builderBottomDargDelTipView(context),
        ],
      ),
    );
  }

  Widget _builderBottomTip(BuildContext context) {
    return Container(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            _builderBottomCheckBox(context),
            _builderBottomButton(context),
          ],
        ),
        decoration: BoxDecoration(color: Colors.white, boxShadow: [
          BoxShadow(
              color: ColorsConfig.c_26000000,
              offset: Offset(0.0, 2.0), //阴影xy轴偏移量
              blurRadius: 15.0, //阴影模糊程度
              spreadRadius: 0.0 //阴影扩散程度
          )
        ]));
  }

  bool checked = true;

  Widget _builderBottomCheckBox(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(15),
          ScreenUtil().setWidth(8),
          ScreenUtil().setWidth(15),
          ScreenUtil().setWidth(8)),
      width: double.infinity,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          InkWell(
            onTap: () {
              setState(() {
                checked = !checked;
                widget.circleData.autoPublish = checked == true ? "YES" : "NO";
                ZhugeCircleAnalysis.circleCheckAuto("编辑动态", checked);
              });
            },
            child: Container(
              padding: EdgeInsets.all(ScreenUtil().setWidth(5)),
              child: checked
                  ? Image.asset('picture/icon_checkbox_checked.png',
                      width: ScreenUtil().setWidth(22),
                      height: ScreenUtil().setWidth(22),
                      package: 'amway_superapp_creator_plugin')
                  : Image.asset('picture/icon_checkbox_unchecked.png',
                      width: ScreenUtil().setWidth(22),
                      height: ScreenUtil().setWidth(22),
                      package: 'amway_superapp_creator_plugin'),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(5)),
            child: Text("保存将自动审核，审核通过后立即发布到创玩小站",
                style: TextStyle(
                    color: ColorsConfig.c_4D2C2C2C,
                    fontSize: ScreenUtil().setSp(14))),
          )
        ],
      ),
    );
  }

  int num = 0;
  bool isSave = false;

  Widget _builderBottomButton(BuildContext context) {
    Color color = ColorsConfig.c_4d396E75;
    if (widget.isDetailEdit) {
      if (widget.isNewAdd) {
        if (widget.circleData.title.isNotEmpty &&
            widget.circleData.description.isNotEmpty &&
            num < 1001 &&
            isAddImage != null &&
            imageList.length > 0) {
          color = ColorsConfig.c_396E75;
        } else {
          color = ColorsConfig.c_4d396E75;
        }
      } else {
        if (widget.circleData.title.isNotEmpty && hasTitle) {
          //标题
          color = ColorsConfig.c_396E75;
        } else if (widget.circleData.description.isNotEmpty && hasDes) {
          //描述
          color = ColorsConfig.c_396E75;
        } else if (imageChanged) {
          //图片
          color = ColorsConfig.c_396E75;
        } else if (shopChanged) {
          //商品
          color = ColorsConfig.c_396E75;
        } else {
          color = ColorsConfig.c_4d396E75;
        }
      }
    } else {
      color = ColorsConfig.c_4d396E75;
    }
    return Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(15), 0, ScreenUtil().setWidth(15), 0),
        width: double.infinity,
        height: ScreenUtil().setWidth(50),
        child: InkWell(
          onTap: throttle(() async {
            await Future.delayed(Duration(milliseconds: 1000));
            _closeFocus();
            ZhugeCircleAnalysis.circleSave("编辑动态");
            if (!widget.isNewAdd) {
              SpUtil.getData("${SpUtil.local_circle_data}${widget.amwayAda}")
                  .then((value) {
                Map<String, dynamic> response = json.decode(value);
                CircleDetailData circleModel =
                CircleDetailData.fromJson(response);
                if (widget.circleData == circleModel &&
                    widget.isDetailEdit == false) {
                  return;
                } else {
                  _save();
                }
              });
            } else {
              _save();
            }
          }),
          child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              color: color,
            ),
            child: Text(
              "保存",
              style: TextStyle(
                  color: Colors.white, fontSize: ScreenUtil().setSp(18)),
            ),
          ),
        ));
  }

  void _save() {
    if (widget.circleData.title.isEmpty) {
      setState(() {
        hasTitle = false;
      });
    }
    if (widget.circleData.description.isEmpty) {
      setState(() {
        hasDes = false;
      });
    }
    if (num > 1000) {
      ToastUtils.showShortToast("请修改字数超过限制的选项");
      return;
    }
    if (imageList.length == 0) {
      setState(() {
        isAddImage = false;
      });
    }
    if (widget.circleData.title.isNotEmpty &&
        widget.circleData.description.isNotEmpty &&
        imageList.length > 0) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return CommTipDialog(
              isEditInfo: true,
              content:
              '保存后将自动审核，审核通过后将${checked ? "发布到创玩小站" : "存为待发布"}，是否确认保存？',
              confirmText: "确认",
              confirmCallback: () {
                Application.router.pop(context);
                showDialog(
                  context: context,
                  builder: (ctx) {
                    return LoadingDialog(
                      canceledOnTouchOutside: false,
                      tipMsg: '正在保存',
                    );
                  },
                );

                List<File> files = [];
                widget.circleData.medias.clear();
                imageList.forEach((element) {
                  if (element.path != null && element.path.startsWith("http")) {
                    widget.circleData.medias.add(ImagesBean(
                        dataType: "IMAGE",
                        data: element.path,
                        officialFlag: "NO"));
                  } else {
                    files.add(element.file == null
                        ? File(element.path)
                        : element.file);
                  }
                });
                UploadImageUtils().uploadMultiImages(files, (data) {
                  widget.circleData.medias.addAll(data);
                  isSave = true;
                  if (widget.isNewAdd) {
                    saveCircle(widget.amwayAda, (back) {
                      Application.router.pop(context);
                      if (back) {
                        if (widget.isUserDraft) {
                          //清除草稿
                          SpUtil.clearData(
                              "${SpUtil.user_circle}${widget.amwayAda}");
                        }
                        ToastUtils.showShortToast("保存成功");
                        if (!widget.isNewAdd && widget.circleState == 1) {
                          eventBus.fire(CircleBackEvent(true));
                        }
                        Application.router.pop(context, "success");
                      } else {
                        ToastUtils.showShortToast("保存失败");
                      }
                    });
                  } else {
                    //更新
                    updateCircle(widget.circleData.id, callback: (result, msg) {
                      Application.router.pop(context);
                      if (result) {
                        ToastUtils.showShortToast("保存成功");
                        if (!widget.isNewAdd && widget.circleState == 1) {
                          eventBus.fire(CircleBackEvent(true));
                        }
                        Application.router.pop(context, "success");
                      } else {
                        ToastUtils.showShortToast(msg);
                      }
                    });
                  }
                });
              },
              dismissCallback: () {
                Application.router.pop(context);
              },
            );
          });
    } else {
      ToastUtils.showShortToast("内容没有填写完成哦");
    }
  }

  Widget _builderBottomDargDelTipView(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: moveAction == MotionEvent.actionUp
          ? null
          : Container(
        width: double.infinity,
        color: Colors.redAccent,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "picture/icons_delete.png",
                package: "amway_superapp_creator_plugin",
              ),
              Text(
                _canDelete ? '松手即可删除' : '拖拽到此处删除',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: ScreenUtil().setSp(14)),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _loadAssets(BuildContext context) async {
    final List<AssetEntity> assets = await pickAssetCamera(
        context, RequestType.image,
        length: imageList.length, maxAssetsCount: 9);

    List<Future<File>> uploadQueue = new List();
    List<ImageBean> mImages = [];
    for (AssetEntity assetEntity in assets) {
      uploadQueue.add(assetEntity.file);
    }
    Future.wait(uploadQueue).then((results) {
      // print(results[0].toString()+results[1]);
      for (int i = 0; i < results.length; i++) {
        mImages.add(ImageBean(file: results[i]));
        widget.circleData.medias.add(ImagesBean(data: results[i].path));
      }
    }).catchError((e) {
      print(e);
    }).whenComplete(() {
      setState(() {
        widget.isDetailEdit = true;
        imageList.addAll(mImages);
      });
    }).asStream();

    // pick Images.
  }

  _saveDraft() {
    showDialog(
        barrierDismissible: true,
        //是否点击空白区域关闭对话框,默认为true，可以关闭
        context: context,
        builder: (BuildContext context) {
          List<ItemMode> list = List<ItemMode>();
          list.add(ItemMode(
              label: '将退出编辑，是否保存草稿？', color: ColorsConfig.c_8f8f8f, size: 15));
          list.add(ItemMode(
              label: '保存草稿并退出', color: ColorsConfig.c_396E75, size: 17));
          list.add(
              ItemMode(label: '继续编辑', color: ColorsConfig.c_396E75, size: 17));
          return CommonBottomSheet(
            list: list,
            onItemClickListener: (index) async {
              Navigator.pop(context);
              switch (index) {
                case 2:
                  if (imageList.length > 0) {
                    widget.circleData.medias.clear();
                    widget.circleData.medias
                        .addAll(coverImagestDatas(imageList));
                  }
                  SpUtil.setData("${SpUtil.user_circle}${widget.amwayAda}",
                      json.encode(widget.circleData));
                  Application.router.pop(context);
                  break;
              }
            },
          );
        });
  }

  List<ImagesBean> coverImagestDatas(List<ImageBean> images) {
    List<ImagesBean> medias = [];
    if (images.length > 0) {
      images.forEach((element) {
        medias.add(ImagesBean(
          dataType: EnumUtils.enumToString(DataType.IMAGE),
          data: element.file == null ? element.path : element.file.path,
        ));
      });
      return medias;
    }
  }

  _clear() {
    widget.circleData.title = "";
    widget.circleData.description = "";
    widget.circleData.medias.clear();
    imageList.clear();
  }

  _closeFocus() {
    if (_titleNode.hasFocus) _titleNode.unfocus();
    if (_descNode.hasFocus) _descNode.unfocus();
  }

  void saveCircle(String ada, BoolCallBack callback) {
    HttpManager().post(
        url: "apis/v1/creator/circles/$ada",
        data: widget.circleData,
        tag: null,
        successCallback: (data) {
          return callback.call(true);
        },
        errorCallback: (data) {
          return callback.call(false);
        });
  }

  void updateCircle(String id, {BoolStringCallBack callback}) {
    HttpManager().put(
        url: "apis/v1/creator/circles/$id",
        data: widget.circleData,
        tag: null,
        successCallback: (data) {
          return callback.call(true, "");
        },
        errorCallback: (data) {
          return callback.call(false, data.message);
        });
  }

  _unPassBack() {
    SpUtil.getData("${SpUtil.local_circle_data}${widget.amwayAda}")
        .then((value) {
      Map<String, dynamic> response = json.decode(value);
      CircleDetailData circleModel = CircleDetailData.fromJson(response);
      if (widget.circleData == circleModel) {
        Application.router.pop(context);
      } else {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) {
              return CommTipDialog(
                content: '返回上一步会丢失当前已编辑信息，是否确认返回？',
                confirmText: "知道了",
                isEditInfo: true,
                closeText: "取消",
                confirmCallback: () {
                  Navigator.pop(context);
                  _clear();
                  Application.router.pop(context);
                },
                dismissCallback: () {
                  Navigator.pop(context);
                },
              );
            });
      }
    });
  }
}
